import { default as SA } from './sensors/sensors';
import request from "@/utils/request";
import { deleteUserIdentity, dynamicHeader, getModelData } from "@/utils/utils";
import config from "@/config";

export function loginCallback(userInfo: { empNo: string; nickName: string }) {
  // 初始化
  SA.init();

  // 注册公共属性，主要是注册platform属性
  SA.registerPage();

  const { empNo, nickName } = userInfo;

  // 这里使用工号作为登录唯一id
  SA.login(empNo);

  // 这里用户属性记录了用户名和工号
  const profile = { nickName, empNo };
  SA.setProfile(profile);
}

//提取token
export const extractToken = async () => {
  // 提取Token
  const tokenValue = await request("/authentication/extractToken", {
    method: "POST",
    data: {},
  });
  return tokenValue;
};

//恢复token
export const refactorToken = async (tokenValue: string) => {
  request("/authentication/refactorToken", {
    method: "POST",
    data: {
      value: tokenValue,
    },
  });
};

//退出单点登录
export const ssoLogout = async () => {
  // 跳转至单点登出页面
  window.location.href =
    window["ssoProxyTarget"] + "fwSecurity/ssoAuth/logout.api?userLoginName=" + (dynamicHeader.current as any)?.userLoginName;
  Cookies.remove("GeeTestUser", { path: '/' })
  Cookies.remove("X-JACP-TOKEN", { path: '/' })
};

//默认退出
export const logout = async (forceLocal = false) => {
  await request("/authentication/logout", {
    method: "POST",
    data: {},
  });
  deleteUserIdentity();
  if (forceLocal) {
    window.location.href = window.location.origin + '/?forceLocal=true'
  } else {
    ssoLogout()
  }
  // 重置验证信息 header
  dynamicHeader.current = {};
};

//链式退出
export const logoutByChain = async () => {
  var result = true;
  try {
    // 添加单点登录验证函数
    const {
      COMMON_CONFIG: { sso, logoutChain },
    } = config;
    // 只要在开启单点登录，并且非强制登录页面登录
    // 才需要从单点登录退出
    const isForceLocal = getModelData('login.loginType') === 'DEFAULT_LOGIN';
    //添加默认登录验证函数，至验证链末尾
    logoutChain.push(logout.bind(null, isForceLocal));
    //前一次的调用结果
    let logoutFnPreResult = undefined;
    //循环同步调用登出链里的函数，让一次的结果为入参, 如果有一个为false则中断
    for (let logoutFn of logoutChain) {
      const logoutFnResult: any = await logoutFn(logoutFnPreResult);
      logoutFnPreResult = logoutFnResult;
      if (!logoutFnResult) {
        result = false;
        break;
      }
    }
  } catch (error) {
    result = false;
  }
  return result;
};